package at.codebase.web.servlets.item;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EImageDao;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.LocalRequest;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class ItemUploadHandler extends HttpServlet {
	
	private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private static ImagesService imagesService = ImagesServiceFactory.getImagesService();
	
	private static int MAX_IMAGE_HEIGHT = 800;
	private static int MAX_IMAGE_WIDTH = 800;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		try {
			
			RequestInformation requestInformation = LocalRequest.create(req);
			if(requestInformation.isUserLoggedIn()){
			
				long itemId = requestInformation.getParameters().getLong("itemId");
				EItem item = EItemDao.getItemById(new Long(itemId));
				
				if(item != null){
	
					Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
					List<BlobKey> blobKeys = blobs.get("uploadFile");
					if(blobKeys.size() == 1){
						BlobKey orgBlobKey = blobKeys.get(0);
						Image orgImage = ImagesServiceFactory.makeImageFromBlob(orgBlobKey);
						
						Transform resizeTransform = ImagesServiceFactory.makeResize(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
						
						try {
							Image image = imagesService.applyTransform(resizeTransform, orgImage);
							
							/**
							 * 
							 */
							FileService fileService = FileServiceFactory.getFileService();
							AppEngineFile file = fileService.createNewBlobFile("image/png");
							
							boolean lock = true;
							@SuppressWarnings("resource")
							FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
							
							ByteBuffer buffer = ByteBuffer.wrap(image.getImageData());
							writeChannel.write(buffer);
							
							writeChannel.closeFinally();
							
							// Now read from the file using the Blobstore API
							BlobKey blobKey = fileService.getBlobKey(file);
							/**
							 * 
							 */
							
							EImage imageEntity = EImage.createItemImage(EUser.key(requestInformation.getUser().getId()),
									EItem.key(item.getId()), blobKey, image.getWidth(), image.getHeight());
							
							EImageDao.addImage(imageEntity);
							
							item.getImageKeys().add(EImage.key(imageEntity.getId()));
							EItemDao.saveItem(item);
							
							//Logging
							if(item.checkSeller(requestInformation.getUser().getId())){
								Log.logItem(requestInformation.getUser().getId(),
										"User(seller) (userid="
												+ requestInformation.getUser().getId()
												+ ") added an image (imageid="+imageEntity.getId()+") to an item (itemid="
												+ (item != null?item.getId():"") + ")");
							}else{
								Log.logItem(requestInformation.getUser().getId(),
										"User(uploader) (userid="
												+ requestInformation.getUser().getId()
												+ ") added an image (imageid="+imageEntity.getId()+") to an item (itemid="
												+ (item != null?item.getId():"") + ")");
							}

							
							
							blobstoreService.delete(orgBlobKey);
							
						}catch (IllegalArgumentException e){
							//Invalid Image...
						}
							
					}
	
				}
				
				res.sendRedirect("/item/upload/"+itemId);
				
			}
			
		}catch(ParameterException e){
			
		}
	}
	
}
